using System;
using Microsoft.Office.Interop.Excel;

namespace ExcelFiller
{
    public class Excel
    {
        private Application app;
        private Workbooks wbks;
        private _Workbook _wbk;
        private Sheets shs;
        private _Worksheet _wsh;

        private string ex = null;
        public string lastError() => ex;

        ~Excel() => close();

        /// <summary>
        /// 填写Excel表格
        /// </summary>
        /// <param name="x">x坐标</param>
        /// <param name="y">y坐标</param>
        /// <param name="value">填表值</param>
        public void fill(int x = 1, int y = 1, string value = "") => _wsh.Cells[y, x] = value;

        /// <summary>
        /// 读取(x,y)的值
        /// </summary>
        /// <param name="x">x坐标</param>
        /// <param name="y">y坐标</param>
        /// <returns>读取到的值</returns>
        public string read(int x = 1, int y = 1) => _wsh.Cells[y, x].Text.ToString(); //.ToString() 似乎可去?

        /// <summary>
        /// 打开Excel文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="sheet">表名</param>
        /// <param name="visible">是否显示Excel界面</param>
        /// <returns>是否成功打开</returns>
        public bool open(string path, string sheet = "Sheet1", bool visible = false)
        {
            try
            {
                app = new Application
                {
                    Visible = visible, //可见性
                    DisplayAlerts = false, //不显示警告
                    //app.Interactive = true, //禁止交互
                    Caption = System.IO.Path.GetFileNameWithoutExtension(path) + " - Excel(工作中)" //窗口标题（部分）
                };
                wbks = app.Workbooks;
                _wbk = wbks.Add(@path);
                shs = _wbk.Sheets;
                _wsh = (_Worksheet)shs.get_Item(sheet);
            }
            catch (Exception exx)
            {
                close();
                ex = "open发生错误：\n" + exx.Message;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 将Excel文件保存在指定位置
        /// </summary>
        /// <param name="path"></param>
        /// <returns>是否成功保存</returns>
        public bool save(string path)
        {
            try
            {
                _wbk.SaveAs(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception exx)
            {
                ex = "save发生错误：\n" + exx.Message;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 关闭Excel文件
        /// </summary>
        /// <param name="savepath">保存路径，默认不保存</param>
        /// <returns>是否成功关闭</returns>
        public bool close(string savepath = null)
        {
            if (savepath != null && !save(savepath))
            {
                ex = "close-" + ex;
                return false;
            }
            try
            {
                _wbk.Close(Type.Missing, Type.Missing, Type.Missing);
                wbks.Close();
                app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//???
            }
            catch (Exception exx)
            {
                ex = "close发生错误：\n" + exx.Message;
                return false;
            }
            return true;
        }
    }
}
